package hello

import(
	"strconv"
	"appengine"
	"appengine/datastore"
	"net/http"
)

func actionAdminProducts(c *appengine.Context, w http.ResponseWriter, r *http.Request) {
	products := listAllProducts(c)
	err := adminTemplates.ExecuteTemplate(w, "products.html", products)
	panicIfErr(err)
}

func actionAdminAddProductForm(c *appengine.Context, w http.ResponseWriter, r *http.Request) {
	err := adminTemplates.ExecuteTemplate(w, "editProduct.html", nil)
	panicIfErr(err)
}

func actionAdminAddProduct(c *appengine.Context, w http.ResponseWriter, r *http.Request) {
	key, err := saveProduct(c, &Product{Name: r.FormValue("name")})
	panicIfErr(err)
	// recipeId may come from editRecipeForm
	// product can be created with this the form
	recipeId := r.FormValue("recipeId")
	if len(recipeId) != 0 {
		http.Redirect(w, r, "/admin/editRecipeForm?id=" + recipeId, http.StatusFound)
	}
	if len(r.FormValue("saveAndContinue")) != 0 {
		http.Redirect(w, r, "/admin/editProductForm?id=" + strconv.FormatInt(key.IntID(), 10), http.StatusFound)
		return
	}
	http.Redirect(w, r, "/admin/products", http.StatusFound)
}

func actionAdminEditProductForm(c *appengine.Context, w http.ResponseWriter, r *http.Request) {
	product, err := getProduct(c, parseInt(r.FormValue("id")))
	if err != nil {
		if err == datastore.ErrNoSuchEntity {
			http.NotFound(w, r)
			return
		}
		panic(err)
	}
	err = adminTemplates.ExecuteTemplate(w, "editProduct.html", product)
	panicIfErr(err)
}

func actionAdminUpdateProduct(c *appengine.Context, w http.ResponseWriter, r *http.Request) {
	id := parseInt(r.FormValue("id"))
	_, err := updateProduct(c, id, &Product{Name: r.FormValue("name")})
	panicIfErr(err)
	if len(r.FormValue("saveAndContinue")) != 0 {
		http.Redirect(w, r, "/admin/editProductForm?id=" + r.FormValue("id"), http.StatusFound)
		return
	}
	http.Redirect(w, r, "/admin/products", http.StatusFound)
}

func actionAdminDeleteProduct(c *appengine.Context, w http.ResponseWriter, r *http.Request) {
	err := deleteProduct(c, parseInt(r.FormValue("id")))
	panicIfErr(err)
	http.Redirect(w, r, "/admin/products", http.StatusFound)
}
